package com.nx.platform.es.bean.modle.agg;

import com.google.common.collect.ImmutableMap;
import org.apache.commons.collections4.MapUtils;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;

import java.util.Map;

/**
 * @author
 * @since 2016年10月15日
 */
public class NumberTermsHandler implements AggFieldHandler {

    @Override
    public TermsAggregationBuilder handle(ImmutableMap<String, ?> fieldConfig, Map<String, ?> params) {
        String fieldName = MapUtils.getString(fieldConfig, "fieldName");
        String sort = MapUtils.getString(params, "sort");
        Integer size = MapUtils.getInteger(fieldConfig, "_size", 20);
        TermsAggregationBuilder termsBuilder = AggregationBuilders.terms("default").field(fieldName);
        if ("term".equalsIgnoreCase(sort) || "term_asc".equalsIgnoreCase(sort)) {
            termsBuilder.order(BucketOrder.key(true));
        } else if ("term_desc".equalsIgnoreCase(sort)) {
            termsBuilder.order(BucketOrder.key(false));
        } else if ("count_asc".equalsIgnoreCase(sort)) {
            termsBuilder.order(BucketOrder.count(true));
        } else {
            termsBuilder.order(BucketOrder.count(false));
        }
        termsBuilder.size(size);
        return termsBuilder;
    }

}
